<?php


namespace app\cms\home\api;


use app\cms\community\thirdPartyApi\weChat\lib\payParams;
use app\cms\community\thirdPartyApi\weChat\User;
use app\cms\model\userOauthKeyModel;
use Exception;
use iflow\Response;
use iflow\Router\Controller;
use iflow\Router\implement\Request\{ GetMapping, PostMapping };
use WeChat\Exceptions\InvalidDecryptException;
use WeChat\Exceptions\InvalidResponseException;
use WeChat\Exceptions\LocalCacheException;

#[Controller('%cmsHome%/authorized')]
class authorized {

    protected User $user;

    /**
     * @throws Exception
     */
    public function __construct() {
        $this->user = new User(new payParams(id: request() -> params('config_id', 1)));
    }

    /**
     * 小程序登录
     * @param string $code 授权code
     * @param string $iv 加密算法的初始向量
     * @param string $encryptedData 加密数据
     * @return Response
     * @throws InvalidDecryptException
     * @throws InvalidResponseException
     * @throws LocalCacheException
     */
    #[PostMapping]
    public function wechatMinApp(string $code, string $iv, string $encryptedData): Response
    {
        if ($code === "") return message() -> unauthorized_error('获取授权失败， 请重试');
        $user = $encryptedData !== "" ?
            $this->user -> userInfo($code, $iv, $encryptedData):
            $this->user -> session($code);
        if (empty($user['openid'])) return message() -> unauthorized_error('获取授权失败， 请重试');
        return (new userOauthKeyModel()) -> login($user);
    }

    /**
     * 微信公众号登录
     * @param string $code
     * @param string $state
     * @param string $scope
     * @param string $redirect 跳转地址
     * @param int $autoRegister
     * @return Response
     */
    #[GetMapping]
    public function wechatCommunity(
        string $code,
        string $state = "",
        string $scope = "snsapi_base",
        string $redirect = "",
        int $autoRegister = 0
    ): Response {
        $_redirect = '/cms/home/api/authorized/wechat_community?config_id='.request() -> params('config_id', 1);
        $_redirect .= '&autoRegister='.$autoRegister;
        $_redirect .= '&redirect='.$redirect;
        if ($code === "") return message() -> setIsRest() -> redirect($this->user -> getOauthRedirect($state, $scope, $_redirect));
        try {
            $user = $this->user -> getWechatCommunityUserInfo($code);
            if ($user) {
                $autoRegister = $autoRegister === 1;
                $user = $this->user -> getUserInfo($user['access_token'], $user['openid']);
                $data = (new userOauthKeyModel()) -> login($user, 'wechat_communityopenid', $autoRegister) -> data;
                if ($data['code'] === 200) {
                    return view('community/notice/wechat_msg', [
                        'msg' => $data['msg'],
                        'info' => '',
                        'btn_text' => '返回上页',
                        'to_url' => $redirect ? $redirect."?authorization={$data['items']['authorization']}" : '/index/home'
                    ]);
                }
                throw new Exception($data['msg'], 401);
            }
            throw new Exception('获取授权失败， 请重试', 401);
        } catch (Exception $exception) {
            return view('community/notice/wechat_msg', [
                'msg' => $exception -> getMessage(),
                'info' => $exception -> getMessage(),
                'btn_text' => '返回上页',
                'to_url' => $redirect ?: '/index/home'
            ]);
        }
    }
}